import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 1. 文件命名函数
def generate_filename(year, semester, student_id):
    """
    生成文件名，例如：GPA_2025_Spring_StudentID123456.csv
    """
    return f"GPA_{year}_{semester}_StudentID{student_id}.csv"

# 2. GPA 绩点计算函数
def calculate_gpa(grades):
    """
    根据成绩和学分计算绩点（GPA）
    """
    grade_point_map = {
        "A": 4.0,
        "B": 3.0,
        "C": 2.0,
        "D": 1.0,
        "F": 0.0
    }

    total_points = 0
    total_credits = 0

    for grade in grades:
        course_grade = grade["grade"]
        credits = float(grade["credits"])

        if course_grade in grade_point_map:
            total_points += grade_point_map[course_grade] * credits
            total_credits += credits
        else:
            print(f"未定义的成绩: {course_grade}，跳过该课程")

    if total_credits > 0:
        gpa = total_points / total_credits
        return round(gpa, 2)
    else:
        return 0.0  # 如果没有学分或成绩，返回0.0

# 3. 使用Selenium模拟浏览器登录并抓取成绩信息
def login_to_system(driver, username, password, login_url):
    """
    登录教务系统
    """
    driver.get(login_url)
    time.sleep(2)  # 等待页面加载

    # 找到用户名和密码输入框并输入
    username_field = driver.find_element(By.ID, "username")  # 替换为实际的输入框ID
    password_field = driver.find_element(By.ID, "password")  # 替换为实际的输入框ID

    username_field.send_keys(username)
    password_field.send_keys(password)
    password_field.send_keys(Keys.RETURN)  # 提交表单

def fetch_grade_info(driver):
    """
    抓取成绩信息
    """
    time.sleep(2)  # 等待页面加载
    grade_button = driver.find_element(By.ID, "grades_button")  # 替换为实际的成绩按钮ID
    grade_button.click()

    time.sleep(2)  # 等待成绩信息加载
    grades_table = driver.find_element(By.ID, "grades_table")  # 替换为实际的成绩表格ID
    rows = grades_table.find_elements(By.TAG_NAME, "tr")

    grade_data = []
    for row in rows:
        cols = row.find_elements(By.TAG_NAME, "td")
        if len(cols) > 1:  # 确保不是空行
            course_name = cols[0].text
            grade = cols[1].text
            credits = cols[2].text
            grade_data.append({"course_name": course_name, "grade": grade, "credits": credits})

    return grade_data

def save_grades_to_file(grades, gpa, filename):
    """
    将成绩数据和GPA保存到CSV文件
    """
    import csv
    with open(filename, mode="w", newline="") as file:
        writer = csv.DictWriter(file, fieldnames=["course_name", "grade", "credits"])
        writer.writeheader()
        for grade in grades:
            writer.writerow(grade)
        
        # 添加GPA到文件的最后一行
        file.write(f"\nGPA: {gpa}\n")

def main():
    # 设置Chrome WebDriver
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

    # 登录信息
    username = "your_username"  # 替换为实际用户名
    password = "your_password"  # 替换为实际密码
    login_url = "https://school.example.edu/login"  # 替换为实际登录URL

    # 生成文件名
    year = "2025"  # 替换为实际年份
    semester = "Spring"  # 替换为实际学期名称
    student_id = "123456"  # 替换为实际学生ID
    filename = generate_filename(year, semester, student_id)

    # 登录到教务系统并抓取成绩信息
    login_to_system(driver, username, password, login_url)
    grades = fetch_grade_info(driver)

    # 计算GPA
    gpa = calculate_gpa(grades)

    # 保存成绩数据和GPA到文件
    save_grades_to_file(grades, gpa, filename)
    print(f"成绩和GPA已保存到 {filename}")

    # 关闭浏览器
    driver.quit()

if __name__ == "__main__":
    main()
